<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="info.modie"
      />
      <van-field
        v-model="user.code"
        type="text"
        label="验证码"
        placeholder="请输入验证码"
        :rules="info.code"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { loginApi } from '@/Api'
import { settoken } from '@/utils/auth.js'

export default {
  data () {
    return {
      user: {
        mobile: '13911111111',
        code: '246810'
      },
      info: {
        modie: [
          { required: true, message: '请填写手机号' },
          { pattern: /^1[2-9]\d{9}$/, message: '请正确输入手机号' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请输入6位数字验证码' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      Toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      try {
        const res = await loginApi(this.user)
        // console.log(res)
        Toast.loading({
          forbidClick: false
        })
        Toast.success('登录成功')
        this.$store.commit('changetoken', res.data.data)
        this.$store.commit('changeuserinfo', {})
        // settoken(res.data.data.token)
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back)
        } else {
          this.$router.push('/layout/home')
        }
      } catch (error) {
        Toast.loading({
          forbidClick: false
        })
        Toast.fail('登录失败')
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
